(function () {
    const css = '/static/plugs/mapLocation/mapLocation.css';
    var mapLocation = function () {
        $(function () {
            var cssElement = document.createElement('link');

            cssElement.setAttribute('rel', 'stylesheet');

            cssElement.setAttribute('href', css);

            document.body.appendChild(cssElement);
        });
    };

    mapLocation.prototype.render = function (elem, data) {
        var defaultOption = {
            defaultLocationLongitude: 116.407466,
            defaultLocationLatitude: 39.904989,
            defaultZoom: 16,
            height: 'calc(95vh - 120px)',
            width: '100%',
            name: ua.randdomString(),
            location: null,
            locationLatitude: null,
            locationLongitude: null
        };

        
        var options = $.extend(defaultOption, data);
        var originalLocation = $(options.location).val();
        var originalLocationLatitude = $(options.locationLatitude).val();
        var originalLocationLongitude = $(options.locationLongitude).val();

        if (!options.key) {
            console.log('请提供天地图API Key');
            return;
        }
        // console.log(options);

        var mapId = options.name;
        var mapContainer = $(`
            <div class="ul-map-location">
                <div class="option ">
                    <div class="layui-btn-container">
                        <div class="layui-btn layui-btn-sm if-close init">打开地图</div>
                        <div class="layui-btn layui-btn-sm if-open cancel">关闭</div>
                        <div class="layui-btn layui-btn-sm if-open reset">重置</div>
                    </div>
                    <div class="if-open search-container">
                        <div class=" search-main">
                            <div class="search-prefix">
                                <div class="search-prefix-item province-name" style="display:none">
                                    <div class="main"></div>
                                    <div class="close">
                                        <i class="layui-icon layui-icon-close"></i>
                                    </div>
                                </div>
                                <div class="search-prefix-item city-name" style="display:none">
                                    <div class="main"></div>
                                    <div class="close">
                                        <i class="layui-icon layui-icon-close"></i>
                                    </div>
                                </div>
                                <input type="text" class="layui-input location-input" placeholder="请输入搜索关键词" />
                            </div>
                            <div class="layui-btn on-search">搜索</div>
                        </div>
                        <div class="search-body" style="display:none">
                            <div class="search-result" style="display:none"></div>
                            <div class="search-result-option">
                                <div class="item" data-option="prev">上一页</div>
                                <div class="item" data-option="next">下一页</div>
                            </div>
                            <div class="search-statistics" style="display:none">
                                <div class="title">推荐的搜索地</div>
                                <div class="list">
                                   
                                </div>
                            </div>
                            <div class="option-body">关闭</div>
                        </div>
                    </div>
                </div>
                <div id="${mapId}"></div>
                <div class="location-message" style="display: none;"></div>
                <div class="error-message" style="display: none;"></div>
            </div>
        `);
        $(elem).css('clear', 'both');
        mapContainer.appendTo(elem);

        var mapContent = $('#' + mapId);
        mapContent.css('height', options.height);
        mapContent.css('width', options.width);
        mapContent.hide();

        var map = null;
        var oldMarker = null;
        // 初始化地图的函数
        function initMap() {
            if (map) return; // 如果地图已经初始化，直接返回
            var normalm = L.tileLayer.chinaProvider('TianDiTu.Normal.Map', {
                key: options.key,
            }),
                normala = L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', {
                    key: options.key,
                }),
                imgm = L.tileLayer.chinaProvider('TianDiTu.Satellite.Map', {
                    key: options.key,
                }),
                imga = L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion', {
                    key: options.key,
                });

            var normal = L.layerGroup([normalm, normala]),
                image = L.layerGroup([imgm, imga]);

            var baseLayers = {
                "地图": normal,
                "影像": image,
            };

            var overlayLayers = {};

            map = L.map(mapId, {
                center: [35.104, 118.3556],
                layers: [normal],
                zoom: 12
            });

            // 多图层切换有问题，需要换成不含form element的方式
            L.control
            .layers(baseLayers, overlayLayers)
            .setPosition('bottomleft')
            .addTo(map);


            map.on('click', function (e) {
                if (oldMarker) {
                    oldMarker.removeFrom(map);
                }
                var marker = L.marker(e.latlng);
                marker.addTo(map);
                oldMarker = marker;

                $.get('//api.tianditu.gov.cn/geocoder', {
                    postStr: JSON.stringify({
                        lon: e.latlng.lng,
                        lat: e.latlng.lat,
                        ver: 1,
                    }),
                    type: 'geocode',
                    tk: options.key
                }, function (response) {
                    if (response.status != 0) {
                        mapContainer.find('.error-message').text('获取位置信息失败，请稍后重试');
                        mapContainer.find('.error-message').show();
                        return;
                    }

                    var address = response.result.formatted_address;
                    var locationLongitude = e.latlng.lng;
                    var locationLatitude = e.latlng.lat;

                    if (options.location) {
                        $(options.location).val(address);
                    }
                    if (options.locationLatitude) {
                        $(options.locationLatitude).val(locationLatitude);
                    }
                    if (options.locationLongitude) {
                        $(options.locationLongitude).val(locationLongitude);
                    }
                });
            });
        }

        // 绑定初始化事件
        mapContainer.find('.init').on('click', function () {
            mapContent.show();
            initMap();
            $(this).hide();
            mapContainer.find('.if-open').show();

            map.on('locationfound', function (e) {
                mapContainer.find('.location-message').html('您当前的位置：' + e.latlng.lat.toFixed(6) + ',' + e.latlng.lng.toFixed(6) + ' <div class="layui-btn layui-btn-xs location-me">我的定位</div>');
                mapContainer.find('.location-me').data('latlng', e.latlng);
                if (!options.locationLatitude || !options.locationLongitude || !$(options.locationLatitude).val() || !$(options.locationLongitude).val()) {
                    map.flyTo(e.latlng, 16);
                }
            });
            map.on('locationerror', function (e) {
                console.error(e);

                mapContainer.find('.location-message').text('获取您的位置失败，请检查您的网络或地理位置服务是否开启');
            });

            mapContainer.find('.location-message').text('正在获取定位...').show();

            if (window.location.protocol === 'http:') {
                $.get('//location.tianditu.gov.cn/data/getCityName',function(r){
                    mapContainer.find('.location-message').html('您的城市位置：' + r.data.lat + ',' + r.data.lng + ' <div class="layui-btn layui-btn-xs location-me">我的定位</div>');
                    mapContainer.find('.location-me').data('latlng', [r.data.lat,r.data.lng]);
                    map.flyTo([r.data.lat,r.data.lng], 12);
                })
            } else {
                map.locate();
            }

            if(oldMarker){
                oldMarker.removeFrom(map);
            }
            if (options.locationLatitude && options.locationLongitude && $(options.locationLatitude).val() && $(options.locationLongitude).val()) {
                var lat = $(options.locationLatitude).val();
                var lng = $(options.locationLongitude).val();
                oldMarker = L.marker([lat, lng]);
                oldMarker.addTo(map);
                map.flyTo([lat, lng], options.defaultZoom);
            }
        });
        mapContainer.on('click', '.location-me', function () {
            var latlng = $(this).data('latlng');
            map.flyTo(latlng, 16);
        });
        // 绑定取消事件
        mapContainer.find('.cancel').on('click', function () {
            mapContent.hide();
            $('.if-open').hide();
            mapContainer.find('.if-close').show();
            mapContainer.find('.location-message').hide();
            mapContainer.find('.error-message').hide();
            // 如果需要销毁地图实例，可以在这里添加相关代码
            // if (map) {
            //     map.remove();
            //     map = null;
            // }
        });

        mapContainer.find('.reset').on('click',function(){
            console.log(options.location);
            
            if (options.location) {
                $(options.location).val(originalLocation)
            }
            if (options.locationLatitude) {
                $(options.locationLatitude).val(originalLocationLatitude)
            }
            if (options.locationLongitude) {
                $(options.locationLongitude).val(originalLocationLongitude)
            }
            
            if(oldMarker){
                oldMarker.removeFrom(map);
            }
            if($(options.locationLatitude).val() && $(options.locationLongitude).val()){
                var lat = $(options.locationLatitude).val();
                var lng = $(options.locationLongitude).val();
                oldMarker = L.marker([lat, lng]);
                oldMarker.addTo(map);
                map.flyTo([lat, lng], options.defaultZoom);
            }
        })

        // 初始状态下隐藏取消按钮
        mapContainer.find('.if-open').hide();

        var searchLoading = false;
        var page = 1;
        function search(isInit) {
            if (isInit) {
                page = 1;
            }
            var keywords = mapContainer.find('.location-input').val();

            if (keywords.length == 0) {
                mapContainer.find('.search-body').hide();
                return;
            }

            var provinceName = mapContainer.find('.province-name .main').text();
            var cityName = mapContainer.find('.city-name .main').text();
            provinceCode = mapContainer.find('.province-name').data('code');
            cityCode = mapContainer.find('.city-name').data('code');


            if (searchLoading) {
                return;
            }
            searchLoading = true;

            // 更新上一页按钮状态 - 第一页时禁用上一页按钮
            mapContainer.find('.search-result-option .item[data-option="prev"]').toggleClass('disabled', page <= 1);

            var searchParams = {
                keyWord: keywords,
                mapBound: '-180,-90,180,90',
                level: 8,
                queryType: '1',
                start: (page - 1) * 10,
                count: 10,
                show: 2,
            };

            // 按照区域搜索
            if (provinceName) {
                delete searchParams.mapBound
                searchParams.queryType = 12
                searchParams.specify = provinceCode;
            }

            if (cityName) {
                delete searchParams.mapBound
                searchParams.queryType = 12
                searchParams.specify = cityCode;
            }

            // 按照拼接关键字搜索
            // if (cityName) {
            //     searchParams.keyWord = cityName + searchParams.keyWord;
            // }
            // if (provinceName) {
            //     searchParams.keyWord = provinceName + searchParams.keyWord;
            // }


            $.get('//api.tianditu.gov.cn/v2/search', {
                postStr: JSON.stringify(searchParams),
                type: 'query',
                tk: options.key
            }, function (resSearch) {
                searchLoading = false;
                page++;
                // 清空搜索结果容器
                var $searchResult = mapContainer.find('.search-result');
                $searchResult.empty();

                // 检查是否有搜索结果
                if (resSearch && resSearch.pois && resSearch.pois.length > 0) {
                    // 遍历搜索结果并添加到容器中
                    $.each(resSearch.pois, function (index, poi) {
                        var lonlatArr = poi.lonlat.split(',');
                        var resultItem = $(`
                            <div class="result-item" data-lng="${lonlatArr[0]}" data-lat="${lonlatArr[1]}" data-name="${poi.name}">
                                <div class="name">${poi.name}</div>
                                <div class="address">${poi.address}</div>
                                <div class="info">
                                    <span class="type">${poi.typeName || ''}</span>
                                    <span class="location">${poi.province} ${poi.city} ${poi.county}</span>
                                </div>
                            </div>
                        `);
                        $searchResult.append(resultItem);
                    });

                    // 显示搜索结果区域
                    $searchResult.show();
                    mapContainer.find('.search-statistics').hide();

                    // 更新下一页按钮状态
                    mapContainer.find('.search-result-option .item[data-option="next"]').toggleClass('disabled', resSearch.pois.length < 10);
                } else {
                    // 没有搜索结果时显示提示
                    $searchResult.html('<div class="no-result">没有找到相关地点</div>');
                    $searchResult.show();

                    // 禁用下一页按钮
                    mapContainer.find('.search-result-option .item[data-option="next"]').addClass('disabled');
                }
                // 更新统计数据
                if (resSearch && resSearch.statistics && resSearch.statistics.allAdmins) {
                    var $statisticsList = mapContainer.find('.search-statistics .list');
                    $statisticsList.empty();

                    $.each(resSearch.statistics.allAdmins, function (index, admin) {
                        var isleaf = admin.isleaf ? '1' : '0';
                        $statisticsList.append(`<div class="item" data-isleaf="${isleaf}" data-name="${admin.adminName}" data-code="${admin.adminCode}">${admin.adminName} ${admin.count}个</div>`);
                    });

                    // 如果没有搜索结果但有推荐地区，显示统计区域
                    if (!resSearch.pois || resSearch.pois.length === 0) {
                        mapContainer.find('.search-statistics').show();
                    }
                }else{
                    mapContainer.find('.search-statistics').hide();
                }
                mapContainer.find('.search-body').show();
            });
        }

        mapContainer.find('.location-input').on('input', function (e) {
            search(true);
        });
        mapContainer.find('.on-search').on('click', function (e) {
            search(true);
        });
        mapContainer.find('.option-body').on('click', function (e) {
            mapContainer.find('.search-body').hide();
        });

        mapContainer.on('click', '.search-statistics .item', function () {
            if ($(this).data('isleaf') == '1') {
                mapContainer.find('.city-name .main').text($(this).data('name'));

                mapContainer.find('.city-name').data('code', $(this).data('code'));
                mapContainer.find('.city-name').show();
            } else {
                mapContainer.find('.province-name .main').text($(this).data('name'));
                mapContainer.find('.province-name').data('code', $(this).data('code'));
                mapContainer.find('.province-name').show();
            }
            search(true);
        });

        mapContainer.on('click', '.search-prefix-item .close', function () {
            $(this).prev().text('');
            $(this).closest('.search-prefix-item').hide();
            search(true);
        });

        // 绑定搜索结果点击事件
        mapContainer.on('click', '.result-item', function () {
            var lng = $(this).data('lng');
            var lat = $(this).data('lat');
            var latlng = L.latLng(lat, lng);

            // 移动地图到选中位置
            map.flyTo(latlng, 16);

            // 添加标记
            if (oldMarker) {
                oldMarker.removeFrom(map);
            }
            var marker = L.marker(latlng);
            marker.addTo(map);
            oldMarker = marker;

            // 更新表单值
            var address = $(this).find('.address').text();
            if (options.location) {
                $(options.location).val(address);
            }
            if (options.locationLatitude) {
                $(options.locationLatitude).val(lat);
            }
            if (options.locationLongitude) {
                $(options.locationLongitude).val(lng);
            }
        });

        // 绑定分页按钮点击事件
        mapContainer.on('click', '.search-result-option .item', function () {
            var option = $(this).data('option');

            if (option === 'prev') {
                if (page > 2) { // 当前页码大于2才能上一页
                    page -= 2; // 因为search函数会自增page，所以这里减2
                    search();
                }
            } else if (option === 'next') {
                // 如果当前结果数量等于10，说明可能有下一页
                var resultCount = mapContainer.find('.search-result .result-item').length;
                if (resultCount === 10) {
                    search();
                }
            }
        });

        return elem;
    };

    window.mapLocation = new mapLocation();
})();